package com.dz.lm.web.controller.comp;

import com.alibaba.fastjson.JSONObject;
import com.dz.lm.common.dto.UserProductDTO;
import com.dz.lm.common.exception.ServiceException;
import com.dz.lm.common.util.FileUploadUtil;
import com.dz.lm.common.util.StringUtil;
import com.dz.lm.common.util.TecentVideo;
import com.dz.lm.common.utils.DateUtil;
import com.dz.lm.common.utils.StringUtils;
import com.dz.lm.common.utils.json.JsonUtils;
import com.dz.lm.domain.compproduct.CompProduct;
import com.dz.lm.service.attach.AttachService;
import com.dz.lm.service.comp.compproduct.CompProductService;
import com.dz.lm.web.controller.Basic2Control;
import com.smartlbs.util.UploadFile;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.util.*;

@Controller
@RequestMapping("/rewriteUrl/comp/product")
public class CompProductController extends Basic2Control {
    @Autowired
    private CompProductService compProductService;
    @Autowired
    private AttachService attachService;
    /**
     * 添加产品
     *
     * @param request
     * @return
     * @throws ServiceException
     */
    @ResponseBody
    @RequestMapping("/add")
    public Map add(HttpServletRequest request) throws ServiceException {
        String result = "01";
        String message = "操作失败";
        Object data = null;
        JSONObject subjo = new JSONObject();
        Object imgUrl = request.getAttribute("imgUrl");
        String reqData = request.getAttribute("_reqData") != null ? request.getAttribute("_reqData").toString() : "";
        //附件
        List<UploadFile> fList = (List<UploadFile>) request.getAttribute("fileField");

        Map<String, Object> urlMap = new HashMap<String, Object>();
        if (fList != null && fList.size()>0) {
            urlMap = FileUploadUtil.uploadByInStream(fList, imgUrl, "product");
        }

        Map<String, Object> param = JsonUtils.readValue(reqData.toString());
        //参数校验
        Vector<String> inparam = new Vector<String>();
        for (String in : inparam) {
            if (!param.containsKey(in)) {
                subjo = new JSONObject();
                subjo.put("result", "01");
                subjo.put("message", "参数" + in + "异常");
                return subjo;
            }
        }

        //公司id
        Integer compId = param.get("compId") != null ? Integer.parseInt(param.get("compId").toString()) : 0;
        //标题
        String title = param.get("title") != null ? param.get("title").toString() : "";
        //产品内容
        String content = param.get("content") != null ? param.get("content").toString() : "";
        //视频地址(关联附件id)
        Integer vedioId = param.get("videoId") != null ? Integer.parseInt(param.get("videoId").toString()) : 0;
        //产品名称
        String projectName = param.get("productName") != null ? param.get("productName").toString() : "";
        //模板json{name:””,...}
        String template = param.get("template") != null ? param.get("template").toString() : "";
        //province	省市编码
        String province = param.get("province") != null ? param.get("province").toString() : "110100";
        //city	城市编码
        String city = param.get("city") != null ? param.get("city").toString() : "";
        //区
        String area = param.get("area") != null ? param.get("area").toString() : "";
        //返点设置
        double returnPoint = param.get("returnPoint") != null ? StringUtil.getDouble( param.get("returnPoint") ,0) : 0.00;
        //代理费用
        double agentCost = param.get("agentCost") != null ? Double.parseDouble(param.get("agentCost").toString()) : 0.00;
        //发放个数
        Integer grantNum = param.get("grantNum") != null ? Integer.parseInt(param.get("grantNum").toString()) : 0;
        //代理排名
        Integer rank = param.get("rank") != null ? Integer.parseInt(param.get("rank").toString()) : 0;
        //代理是否需要审核
        Integer isReview = param.get("isReview") != null ? Integer.parseInt(param.get("isReview").toString()) : 0;
        //代理审核模板json{name:””,...}
        String agentTemplate = param.get("agentTemplate") != null ? param.get("agentTemplate").toString() : "";
        //代理等级json串
        String agentLevel = param.get("agentLevel") != null ? param.get("agentLevel").toString() : "";

        //添加产品

        CompProduct product = new CompProduct();
        if (!"100000".equals(province)) { //全国：100000
            product.setProvince(province);
            //全北京 天津 上海 重庆
            if (!"".equals(city) && !"110100".equals(city) && !"120100".equals(city) && !"310100".equals(city) && !"500100".equals(city))
                product.setCity(city);
        }
        product.setCompId(compId);
        product.setStatus(1);
        product.setTitle(title);
        product.setContent(content);

        if(urlMap.get("imageUrl1") != null){
            product.setImageUrl1(urlMap.get("imageUrl1") != null ? imgUrl + urlMap.get("imageUrl1").toString() : "");
        }
        if(urlMap.get("imageUrl2") != null ){
            product.setImageUrl2(urlMap.get("imageUrl2") != null ? imgUrl + urlMap.get("imageUrl2").toString() : "");

        }
        if(urlMap.get("imageUrl3") != null ){
            product.setImageUrl3(urlMap.get("imageUrl3") != null ? imgUrl + urlMap.get("imageUrl3").toString() : "");

        }
        if(urlMap.get("imageUrl4") != null){
            product.setImageUrl4(urlMap.get("imageUrl4") != null ? imgUrl + urlMap.get("imageUrl4").toString() : "");

        }
        if(urlMap.get("imageUrl5") != null){
            product.setImageUrl5(urlMap.get("imageUrl5") != null ? imgUrl + urlMap.get("imageUrl5").toString() : "");

        }
        product.setAgentLevel(agentLevel);
        product.setTemplate(template);
        product.setArea(area);
        product.setReturnPoint(returnPoint);
        product.setAgentCost(0d);
        product.setGrantNum(0);
        product.setVideoId(vedioId);
        product.setProductName(projectName);
        product.setIsReview(isReview);
        product.setAgentTemplate(agentTemplate);
        try {
            product.setCreateTime(com.smartlbs.util.DateUtil.getNowDateTimeString());
            product.setUpdateTime(com.smartlbs.util.DateUtil.getNowDateTimeString());//发布时间
        } catch (ParseException e) {
            e.printStackTrace();
        }
        if(returnPoint > 0 && StringUtils.getNumberDecimalDigits(returnPoint) > 1) { //判断返点格式
            message = "成交返点请设置为小数点后一位";
            result = "01";
        }else if(agentCost > 0 && StringUtils.getNumberDecimalDigits(agentCost) > 1){ //判断代理金额格式
            message = "代理小费请设置为小数点后一位";
            result = "02";
        }else {
            int add = compProductService.add(product);
            if (add > 0) {
                message = "添加成功";
                result = "00";

            }
        }

        subjo.put("message", message);
        subjo.put("result", result);
        subjo.put("data", data);
        return subjo;
    }
    /**
     * 修改产品
     *
     * @param request
     * @return
     * @throws ServiceException
     */
    @ResponseBody
    @RequestMapping("/update")
    public Map update(HttpServletRequest request) throws ServiceException {
        String result = "01";
        String message = "操作失败";
        Object data = null;
        JSONObject subjo = new JSONObject();
        //登录人
        String uId = request.getAttribute("userId") != null ? request.getAttribute("userId").toString() : "";
        Object imgUrl = request.getAttribute("imgUrl");
        String reqData = request.getAttribute("_reqData") != null ? request.getAttribute("_reqData").toString() : "";
        //附件
        List<UploadFile> fList = (List<UploadFile>) request.getAttribute("fileField");

        Map<String, Object> urlMap = new HashMap<String, Object>();
        if (fList != null && fList.size()>0) {
            urlMap = FileUploadUtil.uploadByInStream(fList, imgUrl, "product");
        }

        Map<String, Object> param = JsonUtils.readValue(reqData.toString());
        //参数校验
        Vector<String> inparam = new Vector<String>();
        inparam.add("productId");
        for (String in : inparam) {
            if (!param.containsKey(in)) {
                subjo = new JSONObject();
                subjo.put("result", "01");
                subjo.put("message", "参数" + in + "异常");
                return subjo;
            }
        }
        //产品
        Integer productId = param.get("productId") != null ? Integer.parseInt(param.get("productId").toString()) : 0;
        //标题
        String title = param.get("title") != null ? param.get("title").toString() : "";
        //产品内容
        String content = param.get("content") != null ? param.get("content").toString() : "";
        //视频地址(关联附件id)
        Integer videoId = param.get("videoId") != null ? Integer.parseInt(param.get("videoId").toString()) : 0;
        //产品名称
        String productName = param.get("productName") != null ? param.get("productName").toString() : "";
        //模板json{name:””,...}
        String template = param.get("template") != null ? param.get("template").toString() : "";
        //是否需要审批
        Integer isReview = param.get("isReview") != null ? Integer.parseInt(param.get("isReview").toString()) : 0;

        //代理申请模板
        String agentTemplate = param.get("agentTemplate") != null ? param.get("agentTemplate").toString() : "";

        //province	省市编码
        String province = param.get("province") != null ? param.get("province").toString() : "110100";
        //city	城市编码
        String city = param.get("city") != null ? param.get("city").toString() : "";
        //区
        String area = param.get("area") != null ? param.get("area").toString() : "";
        //删除视频id
        String deFileId = param.get("deFileId") != null ? param.get("deFileId").toString() : "";
        //删除附件表id
        Integer deVideoId = param.get("deVideoId") != null ? Integer.parseInt(param.get("deVideoId").toString()) : 0;
        //删除附件地址,逗号分隔
        String deFiles = param.get("deFiles") != null ? param.get("deFiles").toString() : "";
        //返点设置
        double returnPoint = param.get("returnPoint") != null ? Double.parseDouble(param.get("returnPoint").toString()) : 0;
        //代理等级json串
        String agentLevel = param.get("agentLevel") != null ? param.get("agentLevel").toString() : "";

        //小程序标识
        String wxcode = param.get("wxcode") != null ? param.get("wxcode").toString() : "";
        String imageUrl1 = param.get("imageUrl1") != null ? param.get("imageUrl1").toString() : "";
        String imageUrl2 = param.get("imageUrl2") != null ? param.get("imageUrl2").toString() : "";
        String imageUrl3 = param.get("imageUrl3") != null ? param.get("imageUrl3").toString() : "";
        String imageUrl4 = param.get("imageUrl4") != null ? param.get("imageUrl4").toString() : "";
        String imageUrl5 = param.get("imageUrl5") != null ? param.get("imageUrl5").toString() : "";
        //修改产品
        CompProduct product = new CompProduct();
        if (!"100000".equals(province)) { //全国：100000
            product.setProvince(province);
            //全北京 天津 上海 重庆
            if (!"".equals(city) && !"110100".equals(city) && !"120100".equals(city) && !"310100".equals(city) && !"500100".equals(city)) {
                product.setCity(city);
            }
        }
        product.setProductId(productId);
        product.setVideoId(videoId);
        if (!StringUtils.isEmpty(productName)) {
            product.setProductName(productName);
        }
        if(videoId>0){
            product.setVideoId(videoId);
        }

        if(returnPoint>-1){
            product.setReturnPoint(returnPoint);
        }
        if (!StringUtils.isEmpty(title)) {
            product.setTitle(title);
        }
        if (!StringUtils.isEmpty(content)) {
            product.setContent(content);
        }
        product.setImageUrl1(imageUrl1);
        product.setImageUrl2(imageUrl2);
        product.setImageUrl3(imageUrl3);
        product.setImageUrl4(imageUrl4);
        product.setImageUrl5(imageUrl5);
        if (urlMap.get("imageUrl1") != null) {
            product.setImageUrl1(imgUrl + urlMap.get("imageUrl1").toString());
        }
        if (urlMap.get("imageUrl2") != null) {
            product.setImageUrl2(imgUrl + urlMap.get("imageUrl2").toString());
        }
        if (urlMap.get("imageUrl3") != null) {
            product.setImageUrl3(imgUrl + urlMap.get("imageUrl3").toString());
        }
        if (urlMap.get("imageUrl4") != null) {
            product.setImageUrl4(imgUrl + urlMap.get("imageUrl4").toString());
        }
        if (urlMap.get("imageUrl5") != null) {
            product.setImageUrl5(imgUrl + urlMap.get("imageUrl5").toString());
        }
        if (!StringUtils.isEmpty(template)) {
            product.setTemplate(template);
        }
        product.setAgentLevel(agentLevel);
        product.setArea(area);
        product.setIsReview(isReview);
        product.setAgentTemplate(agentTemplate);
        product.setUpdateTime(DateUtil.getTimeStr(new Date()));
        int i = compProductService.update(product);
        if(!StringUtils.isEmpty(deFileId)){ //删除视频
            TecentVideo.delete(deFileId);
            attachService.delete(deVideoId);
        }
        if (i > 0) {
            if(!com.smartlbs.util.StringUtil.containEmpty(deFiles)){
                try {
                    for (String s : deFiles.split(",")) {
                        FileUploadUtil.deleteFile(s);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            message = "操作成功";
            result = "00";
        }
        subjo.put("message", message);
        subjo.put("result", result);
        subjo.put("data", data);
        return subjo;
    }
    /**
     * 查询
     * @param request
     * @return
     * @throws ServiceException
     */
    @ResponseBody
    @RequestMapping("/query")
    public Map query(HttpServletRequest request) throws ServiceException {
        String result = "01";
        String message = "";
        Object data = null;
        JSONObject subjo = new JSONObject();
        String reqData = request.getAttribute("_reqData") != null ? request.getAttribute("_reqData").toString() : "";
        Map<String, Object> param = JsonUtils.readValue(reqData.toString());
        Object imgUrl = request.getAttribute("imgUrl");
        Integer pageNum = param.get("pageNum") != null ? Integer.parseInt(param.get("pageNum").toString()) : 1;
        Integer rows = param.get("rows") != null ? Integer.parseInt(param.get("rows").toString()) : 10;
        //公司id
        Integer compId = param.get("compId") != null ? Integer.parseInt(param.get("compId").toString()) : 0;
        if(compId != 0){
            data = compProductService.query(pageNum,rows,compId);
            result ="00";
            message ="获取成功";
        }

        subjo.put("message", message);
        subjo.put("result", result);
        subjo.put("data", data);
        return subjo;
    }
    /**
     * 详情
     * @param request
     * @return
     * @throws ServiceException
     */
    @ResponseBody
    @RequestMapping("/get")
    public Map get(HttpServletRequest request) throws ServiceException {
        String result = "01";
        String message = "";
        Object data = null;
        JSONObject subjo = new JSONObject();
        String reqData = request.getAttribute("_reqData") != null ? request.getAttribute("_reqData").toString() : "";
        Map<String, Object> param = JsonUtils.readValue(reqData.toString());
        Object imgUrl = request.getAttribute("imgUrl");
        //产品id
        Integer productId = param.get("productId") != null ? Integer.parseInt(param.get("productId").toString()) : 0;
        if(productId != 0){
            data = compProductService.get(productId);
            result ="00";
            message ="获取成功";
        }else {
            message = "参数有误";
        }

        subjo.put("message", message);
        subjo.put("result", result);
        subjo.put("data", data);
        return subjo;
    }
}
